package com.photovoltaic.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.entity.RolePermission;
import com.photovoltaic.auth.mapper.RoleMapper;
import com.photovoltaic.auth.mapper.RolePermissionMapper;
import com.photovoltaic.auth.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    
    private final RolePermissionMapper rolePermissionMapper;
    
    @Override
    public Role findByRoleName(String roleName) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getName, roleName);
        return getOne(queryWrapper);
    }

    @Override
    public List<Permission> getRolePermissions(Long roleId) {
        return baseMapper.getRolePermissions(roleId);
    }

    @Override
    @Transactional
    public boolean assignPermission(Long roleId, Long permissionId) {
        // 检查是否已经分配
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId.intValue())
                .eq(RolePermission::getPermissionId, permissionId.intValue());
        if (rolePermissionMapper.selectCount(queryWrapper) > 0) {
            return true;
        }
        
        // 分配权限
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId.intValue());
        rolePermission.setPermissionId(permissionId.intValue());
        return rolePermissionMapper.insert(rolePermission) > 0;
    }
    
    @Override
    @Transactional
    public boolean removePermission(Long roleId, Long permissionId) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId.intValue())
                .eq(RolePermission::getPermissionId, permissionId.intValue());
        return rolePermissionMapper.delete(queryWrapper) > 0;
    }
} 